#include "SegmentViewerWidget.hpp"
#include <qpainter.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdlib.h>

	SegmentViewerWidget::SegmentViewerWidget( SegmentViewerWidget::TSegmentContainerList* containers):
	QGLWidget(),
	currentSegmentContainers(containers)
	{
	
	}
	
	SegmentViewerWidget::~SegmentViewerWidget()
	{
	
	}
	
	void SegmentViewerWidget::initializeGL()
	{
		int width  = 640;
		int height = 480;
		if ( currentSegmentContainers->size() != 0 )
		{
			width  = (*currentSegmentContainers->begin())->GetWidth();
			height = (*currentSegmentContainers->begin())->GetHeight();
		}
		resize( width, height );
		glClearColor( 0.0, 0.0, 0.0, 0.0 );
	}
	
	void SegmentViewerWidget::resizeGL( int width, int height )
	{
		glViewport(0,0,width,height);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluOrtho2D(0,width,0,height);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
	}
	
	void SegmentViewerWidget::paintGL()
	{
		glClear(GL_COLOR_BUFFER_BIT);
		glPixelStorei(GL_UNPACK_ALIGNMENT,1);
		SegmentViewerWidget::TSegmentContainerList::iterator containerIterator;	
		for( containerIterator = currentSegmentContainers->begin(); containerIterator != currentSegmentContainers->end(); ++containerIterator )
		{
			ImageAnalysis::SegmentContainer::TSegmentContainerIterator segmentIterator;
			for( segmentIterator = (*containerIterator)->GetStartSegment(); segmentIterator != (*containerIterator)->GetEndSegment(); ++segmentIterator )
			{			
				glBegin(GL_LINES);
				glColor3f(rand()/(float)RAND_MAX,rand()/(float)RAND_MAX,rand()/(float)RAND_MAX);
				glVertex2i( (*segmentIterator)->begin->x, (*segmentIterator)->begin->y);
				glVertex2i( (*segmentIterator)->end->x, (*segmentIterator)->end->y);
				glEnd();			
			}
		}
		glRasterPos2i(0,0);
		glFlush();
	}
